package com.yydlz.users.Interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yydlz.users.utils.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

//拦截器
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前端将token放在HttpServletRequest请求头中传过来，在这里将token从中拿出来
        //String token = request.getHeader("token");
        String token="";
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("token")){
                    token=cookie.getValue();
                }
            }
        }

        Map<String,Object> map = new HashMap<>();
        try {
            JWTUtils.verify(token);//将token解析成具体的信息，验证令牌
            //以下是验证令牌成功的情况
            return true;           //放行

            //以下是验证令牌不成功的情况
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("msg", "Token已经过期!!!");
        } catch (SignatureVerificationException e){
            map.put("state", false);
            map.put("msg", "签名错误!!!");
        } catch (AlgorithmMismatchException e){
            map.put("state", false);
            map.put("msg", "加密算法不匹配!!!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "无效token~~~");
        }

        //将上面的map转成json
        String json = new ObjectMapper().writeValueAsString(map);
        //设置json格式
        response.setContentType("application/json;charset=UTF-8");
        //返回前端
        response.getWriter().println(json);
        return false;
    }
}
